package com.zhm.demo.ssh;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

public class SSHCommandExecutor {
    public static void main(String[] args) {
        String sshHost = "172.24.71.27";
        int sshPort = 22;
        String sshUser = "hcadmin";
        String sshPassword = "Hithium.com12";
        String command = "ls /"; // 要在远程服务器上运行的命令

        JSch jsch = new JSch();
        Session session = null;
        ChannelExec channelExec = null;

        try {
            // 创建SSH会话
            session = jsch.getSession(sshUser, sshHost, sshPort);
            session.setPassword(sshPassword);

            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            // 连接SSH服务器
            session.connect();

            // 打开执行命令的通道
            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(command);

            // 获取命令执行的输入流（标准输出和标准错误）
            InputStream in = channelExec.getInputStream();
            channelExec.connect();

            // 读取命令的输出
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            }

            // 检查命令是否成功执行（注意：这只是一个简单的示例，实际中可能需要更复杂的错误处理）
            int exitStatus = channelExec.getExitStatus();
            if (exitStatus == 0) {
                System.out.println("Command executed successfully.");
            } else {
                System.out.println("Command execution failed with exit status: " + exitStatus);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭通道和会话
            if (channelExec != null && channelExec.isConnected()) {
                channelExec.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
}
